<?php


namespace app\user\controller;


use think\Config;
use think\Db;

class Order extends Base
{
    public function Cart(){
        $type = cookie('cart_type');
        if (!$type){
            $type = 1;
        }
        $Goods = Db::name('user_cart')->alias('c')->join('zb_goods_mall g','c.goods_id=g.id')
            ->where(['c.user_id'=>$this->user_id,'g.goods_type'=>$type])->field('c.goods_id,c.id,c.num')->select();

        foreach ($Goods as $k=>$v){
            $Goods[$k]['goods'] = Db::name('goods_mall')->find($v['goods_id']);
        }
        $this->assign('goods',$Goods);
        return $this->fetch('Cart');
    }

    /**
     * Notes:加入购物车
     * Time: 2021/12/24  14:56
     * User: Qian
     */
    public function AddCart(){
        if (IsPost()){
            $id = Param('id');
            $Goods = Db::name('goods_mall')->find($id);
            if (!$Goods){
                return ReturnMsg(0,'商品不存在');
            }

            $cart = Db::name('user_cart')->where(['user_id'=>$this->user_id,'goods_id'=>$Goods['id']])->find();
            if ($cart){
                Db::name('user_cart')->where(['id'=>$cart['id']])->setInc('num');
            }else{
                $add['user_id'] = $this->user_id;
                $add['goods_id'] = $Goods['id'];
                $add['num'] = 1;
                Db::name('user_cart')->insert($add);
            }
            $type = cookie('cart_type');
            if (!$type){
                $type = 1;
            }
            $new_cart = Db::name('user_cart')->alias('c')->join('zb_goods_mall g','c.goods_id=g.id')
                ->where(['c.user_id'=>$this->user_id,'g.goods_type'=>$type])->field('c.goods_id,c.id,c.num')->select();
            foreach ($new_cart as $k=>$v){
                $new_cart[$k]['goods'] = Db::name('goods_mall')->find($v['goods_id']);
            }
            $count = array_sum(array_column($new_cart,'num'));

            return ReturnMsg(1,'添加成功',['count'=>$count,'cart'=>$new_cart]);


        }
    }

    public function UpdateCart(){
        if (IsPost()){
            $id = Param('id');
            $record = Db::name('user_cart')->where(['user_id'=>$this->user_id,'id'=>$id])->find();
            if (!$record){
                return ReturnMsg(0,'购物车记录不存在');
            }
            $type = Param('type');
            if ($type == 'add'){
                if (Db::name('user_cart')->where(['id'=>$id])->setInc('num')){
                    return ReturnMsg(1,'更新成功');
                }else{
                    return ReturnMsg(0,'更新失败',['old'=>$record['num']]);
                }
            }
            if ($type == 'reduce'){
                if ($record['num'] <= 1){
                    return ReturnMsg(1,'更新成功');
                }
                if (Db::name('user_cart')->where(['id'=>$id])->setDec('num')){
                    return ReturnMsg(1,'更新成功');
                }else{
                    return ReturnMsg(0,'更新失败',['old'=>$record['num']]);
                }
            }
        }
    }

    /**
     * Notes:购物车移除
     * Time: 2021/12/24  16:54
     * User: Qian
     */
    public function CartDelete(){
        if (IsPost()){
            $id = Param('id');
            $record = Db::name('user_cart')->where(['user_id'=>$this->user_id,'id'=>$id])->find();
            if (!$record){
                return ReturnMsg(0,'购物车记录不存在');
            }
            if (Db::name('user_cart')->where(['id'=>$id])->delete()){
                return ReturnMsg(1,'删除成功');
            }else{
                return ReturnMsg(0,'删除失败');
            }
        }
    }

    /**
     * Notes:确认订单
     * Time: 2021/12/27  9:24
     * User: Qian
     * @return mixed
     */
    public function Confirm(){
        $type = cookie('cart_type');
        if (!$type){
            $type = 1;
        }
        $goods_id = Param('goods_id');
        $cart = Db::name('goods_mall')->where(['id'=>$goods_id])->find();
//        $cart = Db::name('user_cart')->alias('c')->join('zb_goods_mall g','c.goods_id=g.id')
//            ->where(['c.user_id'=>$this->user_id,'g.goods_type'=>$type])->field('c.goods_id,c.id,c.num')->select();
        $total = 0;
//        foreach ($cart as $k=>$v){
//            $goods = Db::name('goods_mall')->find($v['goods_id']);
//            $cart[$k]['goods'] = $goods;
//            $total += $goods['price']*$v['num'];
//        }
        $UserInfo = UserInfo(['id'=>$this->user_id]);
        $UserInfo['recommend_name'] = UserInfo(['id'=>$UserInfo['recommend']])['username'];
//        $province = Db::name('china_area')->where(['id'=>3325])->select();
//        $city = Db::name('china_area')->where(['pid'=>3325])->select();
        //家族 上级
//        $family = Db::name('user_map')->where(['user_id'=>$UserInfo['recommend'],'status'=>1])->select();
        $total = $cart['price'];
        $type = $cart['goods_type'];
        $this->assign('type',$type);
        $this->assign('cart',$cart);
        $this->assign('UserInfo',$UserInfo);
//        $this->assign('province',$province);
//        $this->assign('city',$city);
        $this->assign('total',$total);
//        $this->assign('family',$family);
        $this->assign('map_top',Config::get('map_top'));
        return $this->fetch('Confirm');
    }

    /**
     * Notes:创建订单
     * Time: 2021/12/27  11:14
     * User: Qian
     */
    public function CreateOrder(){
        if (IsPost()){
            $Data = Param();
            $UserInfo = UserInfo(['id'=>$this->user_id]);
//            if ($Data['name'] == '' || $Data['phone'] == '' || $Data['province'] == '' || $Data['city'] == '' || $Data['area'] == '' || $Data['address'] == ''){
//                return ReturnMsg(0,'请填写收货地址');
//            }
//            $area = Db::name('china_area')->where(['id'=>$Data['area']])->value('merger_name'); //混合后
//            $Data['address'] = $area.'-'.$Data['address']; //全称地址
            //家族
//            if (!isset($Data['map']) || $Data['map'] == ''){
//                return ReturnMsg(0,'请选择家族');
//            }
//            $map = Db::name('user_map')->where(['id'=>$Data['map']])->find();
//            if (!$map){
//                return ReturnMsg(0,'家族不存在');
//            }
//            if ($map['status'] != 1){
//                return ReturnMsg(0,'此家族已完结');
//            }
//            $map_level5 = Db::name('user_map')->where(['map_level'=>5,'map_number'=>$map['map_number']])->count();
//            if ($map_level5 >= 9){
//                return ReturnMsg(0,'此家族已完结');
//            }
//            if ($map_level5 == 0){
//                $max_num = 8;
//            }else{
//                $max_num = Db::name('user_map')->where(['map_level'=>5,'map_number'=>$map['map_number']])->max('position');
//            }

//            $map_user_id = array_column($map,'user_id');
//            if (!in_array($UserInfo['recommend'],$map_user_id)){
//                return ReturnMsg(0,'上级不在此家族里');
//            }
//            if ($map['user_id'] != $UserInfo['recommend']){
//                return ReturnMsg(0,'上级不在此家族里');
//            }
            $Goods = Db::name('goods_mall')->where(['id'=>$Data['goods_id']])->find();
            if (!$Goods){
                return ReturnMsg(0,'配套不存在');
            }
            if ($Goods['goods_type'] == 2){
                return ReturnMsg(0,'1000配套暂不开放');
            }
//            if (!in_array($Data['type'],[1,2])){
//                return ReturnMsg(0,'配套类型有误');
//            }
//            if ($Data['type'] == 2){
//                return ReturnMsg(0,'1000配套暂不开放');
//            }
//            $cart = Db::name('user_cart')->alias('c')->join('zb_goods_mall g','c.goods_id=g.id')
//                ->where(['c.user_id'=>$this->user_id,'g.goods_type'=>$Data['type']])->field('c.goods_id,c.id,c.num')->select();
//            if (empty($cart)){
//                return ReturnMsg(0,'购物车里还没有商品');
//            }
//            $total = 0;
//            $match_type = [];
//            foreach ($cart as $k=>$v){
//                $goods = Db::name('goods_mall')->find($v['goods_id']);
//                if (!empty($match_type)){
//                    if (!in_array($goods['goods_type'],$match_type)){
//                        return ReturnMsg(0,'购物车里存在不同类型的配套');
//                    }
//                }else{
//                    array_push($match_type,$goods['goods_type']);
//                }
//                $cart[$k]['goods'] = $goods;
//                $total += $goods['price']*$v['num'];
//            }
            $match_type = $Goods['goods_type'];
            $total = $Goods['price'];
            //检查上级是否有此配套的网图
//            $recommend_map = Db::name('user_map')->where(['user_id'=>$UserInfo['recommend'],'status'=>1,'match_type'=>$match_type[0],'map_level'=>['in',[1,2,3,4]]])->find();
            $recommend_map = Db::name('user_map')->where(['user_id'=>$UserInfo['recommend'],'status'=>1,'match_type'=>$match_type,'map_level'=>['in',[1,2,3,4]]])->find();
            if (!$recommend_map){
                return ReturnMsg(0,'上级领导不存在此配套的网图');
            }
            //每个用户每个配套只能买一次
//            $order_count = Db::name('order_mall')->where(['user_id'=>$UserInfo['id'],'order_type'=>$match_type[0]])->count();
            $order_count = Db::name('order_mall')->where(['user_id'=>$UserInfo['id'],'order_type'=>$match_type])->count();
            if ($order_count > 0){
                return ReturnMsg(0,'此配套已经买过了');
            }
            if ($UserInfo['balance_1'] < $total){
                return ReturnMsg(0,'账户余额不足');
            }
//            $goods_id = array_column($cart,'goods_id');
//            $num = array_column($cart,'num');
            Db::startTrans();
            try {
                Db::name('user_map')->lock(true)->select();
                //扣余额
                $UserSave['balance_1'] = $UserInfo['balance_1'] - $total;
                $UserSave['achievement'] = $UserInfo['achievement'] + $total;
                Db::name('user')->where(['id'=>$UserInfo['id']])->update($UserSave);
                $order_id = date('YmdHis').str_pad($UserInfo['id'],6,0,STR_PAD_LEFT).randNumber();
                $add['order_id'] = $order_id;
                $add['user_id'] = $UserInfo['id'];
                $add['amount'] = $total;
                $add['pay_amount'] = $total;
                $add['pay_type'] = 1;
//                $add['order_type'] = $match_type[0];
//                $add['goods_id'] = implode(',',$goods_id);
//                $add['num'] = implode(',',$num);
                $add['order_type'] = $match_type;
                $add['goods_id'] = $Goods['id'];
                $add['num'] = 1;
//                $add['name'] = $Data['name'];
//                $add['phone'] = $Data['phone'];
//                $add['address'] = $Data['address'];
                $add['status'] = 1; //已支付
                $add['add_time'] = time(); //已支付
                $add['pay_time'] = time(); //已支付
                $id = Db::name('order_mall')->insertGetId($add);
                FinanceAdd($UserInfo['id'],$UserInfo['id'],$total,1,6,'购买商品','','',$id);
                //添加新球记录
                $ballAdd['user_id'] = $this->user_id;
                $ballAdd['recommend_id'] = $UserInfo['recommend'];
                $ballAdd['match_type'] = $add['order_type'];
                $ballAdd['order_id'] = $add['order_id'];
                $ballAdd['pay_amount'] = $add['pay_amount'];
                $ballAdd['add_time'] = time();
                Db::name('user_ball')->insert($ballAdd);
                //加入家族
//                $map_add['user_id'] = $UserInfo['id'];
//                $map_add['cycle'] = $map['cycle'];
//                $map_add['map_number'] = $map['map_number'];
//                $map_add['map_level'] = 5;
//                $map_add['position'] = $max_num + 1;
//                $map_add['add_time'] = time();
//                $map_add['status'] = 1;
//                $map_id = Db::name('user_map')->insertGetId($map_add);

                //添加业绩
                Db::query("call add_recommend_achievement(:id,:amount)",['id'=>$UserInfo['id'],'amount'=>$add['pay_amount']]);
                //直推奖
                DirectReward($UserInfo['id'],$UserInfo['recommend'],$add['pay_amount']);
                //网图奖
//                MapReward($UserInfo['id'],$map_id,$add['pay_amount']);
                //推广奖
                Db::query("call reward3(:user_id,:amount)",['user_id'=>$UserInfo['id'],'amount'=>$add['pay_amount']]);
                //检查网图是否完成
//                CheckMap($map['id']);
                Db::commit();
                return ReturnMsg(1,'支付成功',['order_id'=>$id]);
            }catch (\Exception $e){
                Db::rollback();
                return ReturnMsg(0,'支付失败，请稍后再试');
            }

        }
    }

    public function chooseCity(){
        $Data = Param();
        if ($Data['type'] == 'province'){
            return '';
        }elseif ($Data['type'] == 'city'){
            $pid = $Data['city'];
            $area = Db::name('china_area')->where(['pid'=>$pid])->select();
            $str = '<option value="">请选择</option>';
            if ($area){

                foreach ($area as $k=>$v){
                    $str .= '<option value="'.$v['id'].'">'.$v['name'].'</option>';
                }
                return  $str;
            }else{

                return $str;
            }
        }
    }


    public function OrderList()
    {
        //条件查询
        $Data = Param();
        if (empty($Data)){
            $Data = [
                'order_id'=>'',
//                'begin_time' => '',
//                'end_time' => '',
            ];
        }
        $this->assign('Data',$Data);
        $Where = [];

        if ($Data['order_id'] != ''){
            $Where['order_id'] = ['like','%'.$Data['order_id'].'%'];
        }
        //时间查询
//        if($Data['begin_time'] != '' && $Data['end_time'] == ''){   //只有开始时间没有结束时间
//            $BeginTime = strtotime($Data['begin_time']);
//            $Where['add_time'] = array('egt',$BeginTime );
//        }
//
//        if($Data['begin_time'] == '' && $Data['end_time'] != ''){   //只有结束时间没有开始时间
//            $EndTime = strtotime($Data['end_time']);
//            $Where['add_time'] = array('elt',$EndTime );
//        }
//
//        if($Data['begin_time'] != '' && $Data['end_time'] != ''){   //有开始时间有结束时间
//            $BeginTime = strtotime($Data['begin_time']);
//            $EndTime = strtotime($Data['end_time']);
//            $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
//        }
        $Where['user_id'] = $this->user_id;
        //总记录条数
        $Count = Db::name('order_mall')->where($Where)->count();

        $this->assign('Count', $Count);

        //订单信息
        $List = Db::name('order_mall')->where($Where)->order('id desc')->paginate(13,false,['query'=>$Data]);
        $OrderList = $List->toArray()['data'];
        $this->assign('OrderList', $OrderList);


        //分页
        $this->assign('Page', $List->render());

        return $this->fetch('OrderList');
    }

    public function OrderDetail(){

        $id = Param('id');
        $OrderInfo = Db::name('order_mall')->find($id);
        $goods_ids = explode(',',$OrderInfo['goods_id']);
        $goods_num = explode(',',$OrderInfo['num']);
        $goodslist = [];
        foreach ($goods_ids as $k=>$v){
            $each = Db::name('goods_mall')->find($v);
            $goodslist[$k]['name'] = $each['name'];
            $goodslist[$k]['logo_url'] = $each['logo_url'];
            $goodslist[$k]['unit'] = $each['unit'];
            $goodslist[$k]['num'] = $goods_num[$k];
        }
        $OrderInfo['goodsList'] = $goodslist;
        $this->assign('OrderInfo',$OrderInfo);
        return $this->fetch('OrderDetail');
    }
}